<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="./dist/html2canvas.js"></script>
    <script src="./dist/jspdf.js"></script>
    <script src="./dist/moment.js"></script>
    <title>尾款采购</title>
    <style>
        @media print {
            @page {
                size: A3;
                /* 设置页面方向为横向 */
            }
        }

        body {
            background-color: #fff !important;
            padding: 36px;

        }

        .box {
            margin: 0 auto;
            width: 100%;
            /* padding: 36px 36px 0px 36px; */
        }

        .tb {
            margin-top: 36px;
            background: url(./dist/img_01.png) repeat-y;
            background-position: center top;
            -webkit-font-smoothing: antialiased;
            -moz-osx-font-smoothing: grayscale;
        }

        /* .box{width: 1121px;height: 793px;} */
        .title {
            text-align: center;
            font-size: 30px;
            font-weight: bold;
        }

        .top {
            font-size: 22px;
            margin-bottom: 50px;
        }

        .flex {
            display: flex;
            align-items: center;
            justify-content: space-between;
        }

        .orderTime1 {
            font-size: 12px;
        }

        .orderTime2 {
            font-size: 12px;
        }

        table {
            border-collapse: collapse;
            /* 合并边框 */
            border: 1px solid #000;
            /* 添加统一的边框样式 */
            width: 100%;
            margin-top: 20px;
        }

        th,
        td {
            border: 1px solid #575757;
            padding: 10px 2px 10px 0px;
            font-size: 12px;
            text-align: center;
            min-width: 50px;
        }

        td p {
            text-align: start;
            padding-left: 18px;
            margin: 1px 0;
        }

        th {
            /* background-color: #f2f2f2; */
            /* font-weight: bold; */
        }

        .bottom {
            margin-top: 40px;
        }

        .Approval-info .title {
            text-align: start;
            font-size: 16px;
            border-bottom: 1px solid #e5e5e5;
            padding-bottom: 4px;
            margin-top: 6px;
        }

        #exportButton {
            margin: 10px;
            padding: 8px 16px;
            background-color: #007bff;
            color: #fff;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            position: absolute;
            top: 24px;
            right: 24px;
        }

        #exportButton:hover {
            background-color: #0056b3;
        }
    </style>
</head>

<body>
    <div class="box" id="content">
        <!-- <div class="top flex"><span>订单详细信息打印</span><span>Page 1 of 4</span></div> -->
        <div class="tb">
            <div class="title">云南移动采购订单</div>
            <table>
                <tr>
                    <td>采购订单编号：</td>
                    <td class="order-number"></td>
                    <td>申请单号：</td>
                    <td class="application-number"></td>
                    <td>资金类型：</td>
                    <td class="funds-type"></td>
                </tr>
                <tr>
                    <td>甲方名称：</td>
                    <td class="first-party"></td>
                    <td>合同名称：</td>
                    <td colspan="3" class="first-party-contract"></td>
                </tr>
                <tr>

                    <td>甲方联系人姓名及电话：</td>
                    <td class="first-party-name"></td>
                    <td>合同编号：</td>
                    <td class="contract-number"></td>
                    <td>订单金额（元）：</td>
                    <td class="order-amount"></td>
                </tr>
                <tr>
                    <td>乙方名称：</td>
                    <td class="second-party"></td>
                    <td>合同上限金额：</td>
                    <td class="maximum-contract-amount"></td>
                    <td>已签订单金额（元）：</td>
                    <td class="signed-order-amount"></td>
                </tr>
                <tr>
                    <td>乙方联系人姓名及电话：</td>
                    <td class="second-party-name">/</td>
                    <td>合同有效期：</td>
                    <td class="validity-date">1</td>
                    <td>订单生效时间：</td>
                    <td class="effective-date"></td>
                </tr>
            </table>
            <div id="table-container">
                <table>
                </table>
            </div>
            <table>
                <!-- 主要为了分列 -->
                <tr>
                    <td rowspan="6" colspan="1">其它约定</td>
                </tr>
                <tr>
                    <td colspan="5" style="text-align: start;">
                        框架协议下的任何订单均应在到货（开始施工、提供服务）前或同日签订（发）。甲方不认可任何没有订单的事实履行，除非双方另行签署生效的书面协议予以确认。</td>
                </tr>
                <tr>
                    <td colspan="5" style="text-align: start;">
                        任何订单内容与所属框架协议约定发生冲突的，双方一致同意由甲方选择更有利于甲方利益的内容供双方最终履行；双方对该冲突另行签订书面补充协议予以确认（遍认）的，从其确定。</td>
                </tr>
                <tr>
                    <td colspan="5" style="text-align: start;">未加盖章甲方订单专用章的任何订单不发生法律效力。</td>
                </tr>
                <tr>
                    <td colspan="5" style="text-align: start;">订单一式3份，甲方2份，乙方1份。</td>
                </tr>
                <tr>
                    <td colspan="5" style="text-align: start;">预计到货日期：2021-07-05</td>
                </tr>
                <tr>
                    <td colspan="5">
                        <p>甲方（盖章）：</p>
                        <p>代表签字：</p>
                        <p>下单日期：<span class="orderTime1"></span></p>
                    </td>
                    <td colspan="5">
                        <p>乙方（盖章）：</p>
                        <p>代表签字：</p>
                        <p>下单日期：<span class="orderTime2"></span></p>
                    </td>
                </tr>
            </table>
            <!-- 审批信息 -->
            <div class="Approval-info" id="Approval-info">
                <div class="title">审批意见</div>
            </div>
            <div class="bottom flex"><span class="botton-url"></span><span class="print-time"></span></div>
        </div>
    </div>
    <button id="exportButton">导出</button>
    <script>
        // 获取要导出的HTML元素
        const element = document.getElementById('content')
        // 使用 html2pdf 将 HTML 元素导出为 PDF
        exportButton.addEventListener('click', () => {
            document.getElementById("exportButton").hidden = true
            window.print()
            document.getElementById("exportButton").hidden = false
        })
    </script>
    <script>

        var queryString = window.location.search
        var urlParams = new URLSearchParams(queryString)
        var id = urlParams.get('id')

        // 上面表格数据
        var info = {
            purchaseOrderNo: "APO304689210500249", // 采购订单编号
            applyOrderNo: "KM-REQ-3046892021050524", // 申请单号
            fundType: "资本", // 资金类型
            partyAName: "中国移动通信集团云南有限公司", // 甲方名称
            contractName: "正常中国移动云南公司昆明分公司2019-2020年社区、无线深度覆盖施工安装项目框架合同（标段一 云南北极光）参保", // 合同名称
            partyAContactName: "戴宣鸿", // 甲方联系人姓名及电话
            contractNo: "KM工建20190936", // 合同编号
            orderAmount: "7262.13", // 订单金额（元）
            partyBName: "云南北极光数码科技有限公司", // 乙方名称
            contractMaxAmount: "28652831.81", // 合同上限金额
            signedOrderAmount: "15703214.58",   // 已签订单金额（元）
            partyBContactName: '/', // 乙方联系人姓名及电话
            contractValidPeriod: '2020-12-31', // 合同有效期
            orderEffectiveTime: '2021-05-31',// 订单生效时间
            print_time: '2023年10月10日',// 打印时间
            createBillTime: '2020-12-31',
            url: 'https://s1.imagehub.cc/images/2023/11/13/09e297b0fb1376b4d71a570e72dd2683.png' // 底部链接
        }

        // 用于动态填充用户信息的函数
        function fillUserInfo() {
            document.querySelector('.order-number').innerText = info.purchaseOrderNo
            document.querySelector('.application-number').innerText = info.applyOrderNo
            document.querySelector('.funds-type').innerText = info.fundType
            document.querySelector('.first-party').innerText = info.partyAName
            document.querySelector('.first-party-contract').innerText = info.contractName
            document.querySelector('.first-party-name').innerText = info.partyAContactName
            document.querySelector('.contract-number').innerText = info.contractNo
            document.querySelector('.order-amount').innerText = info.orderAmount
            document.querySelector('.second-party').innerText = info.partyBName
            document.querySelector('.maximum-contract-amount').innerText = info.contractMaxAmount
            document.querySelector('.signed-order-amount').innerText = info.signedOrderAmount
            document.querySelector('.second-party-name').innerText = info.partyBContactName
            document.querySelector('.validity-date').innerText = info.contractValidPeriod
            document.querySelector('.effective-date').innerText = moment(info.orderEffectiveTime).format('YYYY-MM-DD')
            // document.querySelector('.print-time').innerText = info.print_time
            // document.querySelector('.botton-url').innerText = info.url
            document.querySelector('.orderTime1').innerText = info.createBillTime
            document.querySelector('.orderTime2').innerText = info.createBillTime
        }
        function fillPaymentTable(tableName, data, headers, isNeedTotal) {
            // 模拟数据
            var data = data

            // 获取表格容器
            var tableContainer = document.getElementById(tableName)

            // 创建表格元素
            var table = document.createElement('table')
            // table.setAttribute('border', '1')

            // 创建表头
            var thead = document.createElement('thead')
            var headerRow = document.createElement('tr')
            var headers = headers

            for (var i = 0; i < headers.length; i++) {
                var th = document.createElement('th')
                th.appendChild(document.createTextNode(headers[i]))
                headerRow.appendChild(th)
            }

            thead.appendChild(headerRow)
            table.appendChild(thead)

            // 创建表格内容
            var tbody = document.createElement('tbody')

            for (var i = 0; i < data.length; i++) {
                var row = document.createElement('tr')

                for (var key in data[i]) {
                    var cell = document.createElement('td')
                    cell.appendChild(document.createTextNode(data[i][key] || ''))
                    row.appendChild(cell)
                }

                tbody.appendChild(row)
            }
            if (isNeedTotal) {
                // 添加合计行
                var totalRow = document.createElement('tr')
                var emptyColumns = Object.keys(data[0]).map(function () { return '' })

                // 设置“合计”文本
                emptyColumns[0] = '合计'

                // 计算“不含税总价”和“含税总价”列的合计
                var totalPriceExclTaxSum = data.reduce(function (sum, item) {
                    return sum + parseFloat(item.total_price_excl_tax || 0)
                }, 0)
                emptyColumns[10] = totalPriceExclTaxSum.toFixed(2)

                var totalPriceInclTaxSum = data.reduce(function (sum, item) {
                    return sum + parseFloat(item.total_price_incl_tax || 0)
                }, 0)
                emptyColumns[14] = totalPriceInclTaxSum.toFixed(2)

                // 创建合计行
                emptyColumns.forEach(function (value) {
                    var cell = document.createElement('td')
                    cell.appendChild(document.createTextNode(value))
                    totalRow.appendChild(cell)
                })

                tbody.appendChild(totalRow)
            }
            table.appendChild(tbody)

            // 将表格添加到容器中
            tableContainer.appendChild(table)
        }
        let data1 = [
            // { id: "1", material_code: "M002", material_name: "物料2", project_code: "P002", project_name: "项目2", procurement_type: "二级集采", mis_purchaseOrderNo: "APO789012", unit: "个", quantity: "20", unit_price_excl_tax: "8", total_price_excl_tax: "160", tax_rate: "9%", tax_amount: "14.4", unit_price_incl_tax: "16", total_price_incl_tax: "320", delivery_location: "地点2", fund_location: "资金地2" },
            // { id: "2", material_code: "M002", material_name: "物料2", project_code: "P002", project_name: "项目2", procurement_type: "二级集采", mis_purchaseOrderNo: "APO789012", unit: "个", quantity: "20", unit_price_excl_tax: "8", total_price_excl_tax: "160", tax_rate: "9%", tax_amount: "14.4", unit_price_incl_tax: "16", total_price_incl_tax: "320", delivery_location: "地点2", fund_location: "资金地2" },
            // ... 可以继续添加更多的模拟数据
        ]
        let headers1 = ["序号", "物料编码", "物料名称", "项目编码", "项目名称", "集采类型", "MIS订单号", "单位", "数量", "不含税单价（元）", "不含税总价（元）", "税率", "税额", "含税单价", "含税总价", "到货地点", "资金归属地"]
        let data2 = [
            // { id: "1", taskName: "订单拟稿人创建", taskType: "昆明分公司.工程建设中心", approval_opinion: "请审核", approval_name: "戴宣鸿", approval_date: "2021-05-31 15:14:22" },
            // { id: "2", taskName: "订单拟稿人创建", taskType: "昆明分公司.工程建设中心", approval_opinion: "请审核", approval_name: "戴宣鸿", approval_date: "2021-05-31 15:14:22" },
            // ... 可以继续添加更多的模拟数据
        ]
        let headers2 = ["序号", "任务名称", "任务组别", "审批意见", "审批人", "审批完成时间"]
        window.onload = function () {
            fetch('http://api.ynjov.com:8080/api/getTailOrderDetail/' + id)
                .then(response => {

                    if (!response.ok) {
                        throw new Error('Network response was not ok')
                    }
                    return response.json()
                })
                .then(({ data, items, aproves }) => {
                    info = data
                    data1 = items.map((item, index) => {
                        item.taxRate = item.taxRate.indexOf('%') > -1 ? item.taxRate : (item.taxRate + '%')
                        delete item.id
                        delete item.createdAt
                        delete item.updatedAt
                        delete item.tailOrderId
                        return {
                            index: index + 1,
                            ...item
                        }
                    })
                    data2 = aproves.map((item, index) => {
                        delete item.id
                        delete item.createdAt
                        delete item.updatedAt
                        delete item.tailOrderId
                        return {
                            index: index + 1,
                            ...item,
                            approveFinishTime: moment(item.approveFinishTime).format('YYYY-MM-DD HH:mm:ss')
                        }
                    })
                    fillUserInfo()
                    fillPaymentTable('table-container', data1, headers1, 1)
                    fillPaymentTable('Approval-info', data2, headers2)
                })
                .catch(error => {
                    console.error('Fetch error:', error)
                })
        };
    </script>
</body>

</html>